import json
from http.client import responses
import base64
import pickle
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU


# Create your views here.
class CartsView(View):

    def post(self, request):
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')

        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '商品不存在'})

        try:
            count = int(count)
        except Exception:
            count = 1

        user = request.user
        if user.is_authenticated:
            # 登录用户
            redis_cli = get_redis_connection('carts')
            pipeline = redis_cli.pipeline()
            # redis_cli.hset('carts_%s' % user.id, sku_id, count)
            pipeline.hincrby('carts_%s' % user.id, sku_id, count)
            pipeline.sadd('selected_%s' % user.id, sku_id)
            pipeline.execute()
            return JsonResponse({'code': 0, 'errmsg': '添加购物车成功'})
        else:
            # 未登录用户
            cookie_carts = request.COOKIES.get('carts')
            if cookie_carts:
                carts = pickle.loads(base64.b64decode(cookie_carts))
            else:
                carts = {}
            if sku_id in carts:
                origin_count = carts[sku_id]['count']
                count += origin_count
            #     carts[sku_id]={
            #         'count': count,
            #        'selected': True
            #     }
            # else:
            carts[sku_id] = {
                'count': count,
                'selected': True
            }
            carts_bytes = pickle.dumps(carts)

            base64encoded = base64.b64encode(carts_bytes)
            response = JsonResponse({'code':0,'errmsg':'ok'})
            response.set_cookie('carts', base64encoded.decode(),max_age=3600*24*12)
            return response

    def get(self, request):
        user = request.user

        if user.is_authenticated:
            # 登录用户
            redis_cli = get_redis_connection('carts')
            sku_id_count = redis_cli.hgetall('carts_%s' % user.id)
            select_ids = redis_cli.smembers('selected_%s' % user.id)
            carts = {}
            for sku_id, count in sku_id_count.items():
                sku_id = int(sku_id.decode())
                count = int(count.decode())
                carts[sku_id] = {
                    'count': count,
                   'selected': sku_id in select_ids
                }

        else:
            cookie_carts = request.COOKIES.get('carts')
            if cookie_carts:
                carts = pickle.loads(base64.b64decode(cookie_carts))
            else:
                carts = {}

        sku_ids = carts.keys()
        skus = SKU.objects.filter(id__in=sku_ids)

        sku_list = []
        for sku in skus:
            sku_list.append({
                'id': sku.id,
                'price': sku.price,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'selected': carts[sku.id]['selected'],
                'count': int(carts[sku.id]['count']),
                'amount': sku.price * carts[sku.id]['count']
            })
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_skus': sku_list})

    def put(self, request):
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')
        selected = data.get('selected')
        user = request.user

        if not all([sku_id, count]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '商品不存在'})

        try:
            count = int(count)
        except Exception:
            count = 1

        if user.is_authenticated:
            redis_cli = get_redis_connection('carts')
            redis_cli.hset('carts_%s' % user.id, sku_id, count)
            if selected:
                redis_cli.sadd('selected_%s' % user.id, sku_id)
            else:
                redis_cli.srem('selected_%s' % user.id, sku_id)
            return JsonResponse({'code': 0, 'errmsg': '修改购物车成功'})
        else:
            cookie_carts = request.COOKIES.get('carts')
            if cookie_carts:
                carts = pickle.loads(base64.b64decode(cookie_carts))
            else:
                carts = {}
            if sku_id in carts:
                carts[sku_id] = {
                    'count': count,
                   'selected': selected
                }
            new_carts = base64.b64encode(pickle.dumps(carts))
            response = JsonResponse({'code': 0, 'errmsg': 'ok','cart_sku':{'count':count,'selected':selected}})
            response.set_cookie('carts', new_carts.decode(), max_age=3600*24*14)
            return response

    def delete(self, request):
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        user = request.user

        if not sku_id:
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '商品不存在'})

        if user.is_authenticated:
            redis_cli = get_redis_connection('carts')
            redis_cli.hdel('carts_%s' % user.id, sku_id)
            redis_cli.srem('selected_%s' % user.id, sku_id)
            return JsonResponse({'code': 0, 'errmsg': '删除购物车成功'})
        else:
            cookie_carts = request.COOKIES.get('carts')
            if cookie_carts is not None:
                carts = pickle.loads(base64.b64decode(cookie_carts))
            else:
                carts = {}
            del carts[sku_id]
            new_carts = base64.b64encode(pickle.dumps(carts))
            response = JsonResponse({'code': 0, 'errmsg': 'ok'})
            response.set_cookie('carts', new_carts.decode(), max_age=3600*24*14)
            return response

class CartsSelectAllView(View):

    def put(self, request):
        data = json.loads(request.body.decode())
        selected = data.get('selected')
        user = request.user

        if selected:
            if not isinstance(selected, bool):
                return JsonResponse({'code': 400, 'errmsg': '参数selected有误'})

        if user.is_authenticated:
            redis_cli = get_redis_connection('carts')
            cart = redis_cli.hgetall('carts_%s' % user.id)
            sku_id_list = cart.keys()
            if selected:
                redis_cli.sadd('selected_%s' % user.id, *sku_id_list)
            else:
                redis_cli.srem('selected_%s' % user.id, *sku_id_list)
            return JsonResponse({'code': 0, 'errmsg': '全选购物车成功'})
        else:
            cookie_carts = request.COOKIES.get('carts')
            if cookie_carts:
                carts = pickle.loads(base64.b64decode(cookie_carts))
            else:
                carts = {}
            for sku_id in carts:
                carts[sku_id]['selected'] = selected
            new_carts = base64.b64encode(pickle.dumps(carts))
            response = JsonResponse({'code': 0, 'errmsg': 'ok'})
            response.set_cookie('carts', new_carts.decode(), max_age=3600*24*14)
            return response

class CartsSimpleView(View):

    def get(self, request):
        user = request.user

        if user.is_authenticated:
            # 登录用户
            redis_cli = get_redis_connection('carts')
            carts = redis_cli.hgetall('carts_%s' % user.id)
            carts_selected = redis_cli.smembers('selected_%s' % user.id)
            cart_dict = {}
            for sku_id, count in carts.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in carts_selected
                }
        else:
            cookie_carts = request.COOKIES.get('carts')
            if cookie_carts:
                cart_dict = pickle.loads(base64.b64decode(cookie_carts))
            else:
                cart_dict = {}

        cart_skus = []
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict[sku.id]['count'],
                'default_image_url': sku.default_image.url,
            })
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_skus': cart_skus})